#! /usr/bin/env python
# -*- coding: utf-8 -*-

import time
import os
import json
import random

import FileHostProtoType


class rsitem(FileHostProtoType.HostItem):
    pass

class shareflare(FileHostProtoType.FileHostProcess):   
    HOST_URL = "http://shf.wm-panel.com/" 
    SEQUENCE = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'
             
    def __init__(self, user, pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "Shareflare" 
        self._opener = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
        self.logtype = 'poster'
        self._cookieCurl = self._user + '_%s.cookie' % self.hostname
        self._cookieCurl = os.path.join(os.path.dirname(__file__), self._cookieCurl)
    
    LOGIN_URL = 'http://shf.wm-panel.com/wm-panel/User/signin-do'            
    def login(self):  
              
        self.generateOpener()
        # if self.islogin:
            # return True
        if self.restore_cookiejar():
            return True
        self.fherr.write('login to %s %s/%s...' % (self.hostname, self._user,'*'*len(self._pwd)))
        loginData = {'log' : self._user, 
                     'pas' : self._pwd,
                     'inout' : 'Login'
                     }
        loginresult =  self.loginFileHost(
                    self.LOGIN_URL, 
                    loginData
                    )
        # you always see you username at the top of the page, if login successfully.
        if self._user.lower() not in loginresult.lower():
            self.fherr.write(loginresult)
            self.fherr.write("User %s Failed to Login %s." % (self._user, self.hostname))
            return False
        self.fherr.write("User %s logined." % self._user)
        self._cj.save(self._cookieCurl, ignore_discard=True)
        self.islogin = True
        return True
    
    def restore_cookiejar(self):
        '''
        load cookie file, then access website to verify if cookie is avaiable
        '''
        if os.path.isfile(self._cookieCurl):
            self.fherr.write('Restore Local Cookie.')
            try:
                self._cj.load(self._cookieCurl, ignore_discard=True)
            except:
                self.fherr.write('Failed to Restore Local CookieJar.')
            #access website to conferm cookie is avaiable
            return self.check_cookie()
        return False  

    def check_cookie(self):
        self.fherr.write('Checking Cookie...')
        response = self.post_request(self.HOST_URL)
        if response and self._user in response:
            self.fherr.write("User %s Status : Logined." % self._user)
            self.islogin = True             
            return True
        self.fherr.write("[%s]User %s Status : not Logined." % (time.ctime(), self._user))
        self.fherr.write(response)
        return False
    
    def get_random(self):
        str = ''
        length = len(self.SEQUENCE)
        i = 40
        while i > 0:
            str += self.SEQUENCE[random.randint(0,length-1)]
            i -= 1
        return str
    
    UPLOAD_PAGE = 'http://shf.wm-panel.com/wm-panel/Upload'        
    def upload_web(self, file, progressLog=None, other_args=None, send_range=None):
        data ={}
        indexpage = self.post_request(self.UPLOAD_PAGE)
        keys = ['MAX_FILE_SIZE','owner','pin','base','host','source']
        for k in keys:
            v = self.get_upload_key(indexpage, 'name="%s"' % k, -2)
            assert v, "Failed to get upload params %s." % k
            data[k] = v
        
        ACUPL_UPLOAD_SERVER = self.get_upload_key(indexpage, 'ACUPL_UPLOAD_SERVER', -2, "'")
        assert ACUPL_UPLOAD_SERVER, "Failed to get upload server."
        
        
        uid = ("%x" % int(self.get_timeticket())).upper() + '_' + self.get_random()
        upload_link = "http://%(server)s/marker=%(uid)s" % \
                        {'server':ACUPL_UPLOAD_SERVER,
                         'uid':uid}  
                                          
        filesize = os.path.getsize(file)
        filename = self.rename_func(file)
        start_point = 0
        info = "Uploading...%s" % file
        if send_range is not None:
            #range is a 3-tuple, <start, end, number>
            filesize = send_range[1] - send_range[0] + 1
            filename += ".%03d" % send_range[2]
            start_point = send_range[0]
            info += " part%d" % send_range[2]
        
        fileobj = open(file, 'rb')
        fileobj.seek(start_point) 
        data['file0'] = fileobj
        self.fherr.write(info)

        callback = None
        if progressLog is not None:
            callback = progressLog.write
        result = self.post_request(upload_link, data, retry=1, cb=callback, setfilename=filename, setfilesize=filesize)
        #result#
        result_link = "http://shf.wm-panel.com/acupl_proxy.php?srv=%s&uid=%s" % (ACUPL_UPLOAD_SERVER, uid)
        print result_link
        show_files_link = "http://shf.wm-panel.com/wm-panel/File-Manager"
        retry = 5
        while retry > 0:
            result = self.post_request(result_link)
            result = json.loads(result)
            if result['code'] == 200:
                temp_file_link = result['post_result']
                if result['filename']:
                    filename = result['filename']
                live_uid = temp_file_link.split('/')[-1]
                files_page = self.post_request(show_files_link)
                filelink = self.get_upload_key(files_page, live_uid, -2, "'")
                fileid = self.get_upload_key(files_page, live_uid, 3, "'")
                item = rsitem(os.path.basename(file), 'file', fileid, filelink, filename)
                self.newupload.append(item)
                self.fhout.write(item.format()) 
                return item
            retry -= 1
            time.sleep(10)
        self.fherr.write("Failed to upload?")
        self.fherr.write(str(result))